<template>
  <div class="container">
    <Breadcrumb :items="['menu.blog', 'menu.blog.list']" />
    <a-card class="general-card" :title="$t('menu.blog.list')">
      <a-row>
        <a-col :flex="1">
          <a-form
            :model="formModel"
            :label-col-props="{ span: 6 }"
            :wrapper-col-props="{ span: 18 }"
            label-align="left"
          >
            <a-row :gutter="16">
              <a-col :span="8">
                <a-form-item field="title" :label="$t('blogList.form.title')">
                  <a-input
                    v-model="formModel.title"
                    :placeholder="$t('blogList.form.title.placeholder')"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item
                  field="publishedAtStart"
                  :label="$t('blogList.form.publishedAtStart')"
                >
                  <a-date-picker
                    v-model="formModel.publishedAtStart"
                    format="YYYY-MM-DD HH:mm:ss"
                    show-time
                    :time-picker-props="{ defaultValue: '00:00:00' }"
                    style="width: 100%"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item
                  field="publishedAtEnd"
                  :label="$t('blogList.form.publishedAtEnd')"
                >
                  <a-date-picker
                    v-model="formModel.publishedAtEnd"
                    format="YYYY-MM-DD HH:mm:ss"
                    show-time
                    :time-picker-props="{ defaultValue: '23:59:59' }"
                    style="width: 100%"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="status" :label="$t('blogList.form.status')">
                  <a-select
                    v-model="formModel.status"
                    :options="statusOptions"
                    :placeholder="$t('blogList.form.selectDefault')"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
        <a-divider style="height: 84px" direction="vertical" />
        <a-col :flex="'86px'" style="text-align: right">
          <a-space direction="vertical" :size="18">
            <a-button type="primary" @click="search">
              <template #icon>
                <icon-search />
              </template>
              {{ $t('blogList.form.search') }}
            </a-button>
            <a-button @click="reset">
              <template #icon>
                <icon-refresh />
              </template>
              {{ $t('blogList.form.reset') }}
            </a-button>
          </a-space>
        </a-col>
      </a-row>
      <a-divider style="margin-top: 0" />
      <a-row style="margin-bottom: 16px">
        <a-col :span="12">
          <a-space>
            <a-button type="primary" @click="handleClick">
              <template #icon>
                <icon-plus />
              </template>
              {{ $t('blogList.operation.create') }}
            </a-button>
          </a-space>
        </a-col>
        <a-col
          :span="12"
          style="display: flex; align-items: center; justify-content: end"
        >
          <a-tooltip :content="$t('blogList.actions.refresh')">
            <div class="action-icon" @click="search"
              ><icon-refresh size="18"
            /></div>
          </a-tooltip>
          <a-dropdown @select="handleSelectDensity">
            <a-tooltip :content="$t('blogList.actions.density')">
              <div class="action-icon"><icon-line-height size="18" /></div>
            </a-tooltip>
            <template #content>
              <a-doption
                v-for="item in densityList"
                :key="item.value"
                :value="item.value"
                :class="{ active: item.value === size }"
              >
                <span>{{ item.name }}</span>
              </a-doption>
            </template>
          </a-dropdown>
          <a-tooltip :content="$t('blogList.actions.columnSetting')">
            <a-popover
              trigger="click"
              position="bl"
              @popup-visible-change="popupVisibleChange"
            >
              <div class="action-icon"><icon-settings size="18" /></div>
              <template #content>
                <div id="tableSetting">
                  <div
                    v-for="(item, index) in showColumns"
                    :key="item.dataIndex"
                    class="setting"
                  >
                    <div style="margin-right: 4px; cursor: move">
                      <icon-drag-arrow />
                    </div>
                    <div>
                      <a-checkbox
                        v-model="item.checked"
                        @change="
                          handleChange($event, item as TableColumnData, index)
                        "
                      >
                      </a-checkbox>
                    </div>
                    <div class="title">
                      {{ item.title === '#' ? '序列号' : item.title }}
                    </div>
                  </div>
                </div>
              </template>
            </a-popover>
          </a-tooltip>
        </a-col>
      </a-row>
      <a-table
        row-key="id"
        :loading="loading"
        :pagination="pagination"
        :columns="(cloneColumns as TableColumnData[])"
        :data="renderData"
        :bordered="false"
        :size="size"
        @page-change="onPageChange"
      >
        <template #createdAt="{ record }">
          {{ moment(record.createdAt*1000).format('YYYY-MM-DD HH:mm:ss') }}
        </template>

        <template #updateAt="{ record }">
          {{ moment(record.updatedAt*1000).format('YYYY-MM-DD') }}
        </template>

        <template #status="{ record }">
          <span v-if="record.status === 1" class="circle"></span>
          <span v-else class="circle pass"></span>
          {{ $t(`blogList.form.status.${record.status}`) }}
        </template>
        <template #operations="{ record }">
          <a-button v-permission="['admin']" type="text" size="small">
            {{ $t('blogList.columns.operations.view') }}
          </a-button>

          <a-popconfirm content="确认要删除吗?" @ok="optDelBlog(record.id)">
            <a-button
              v-permission="['admin']"
              type="text"
              size="small"
              status="danger"
            >
              删除
            </a-button>
          </a-popconfirm>
        </template>
      </a-table>
    </a-card>
    <a-modal
      v-model:visible="addVisible"
      title="新增文章"
      @cancel="addCancel"
      @before-ok="handleBeforeOk"
    >
      <a-form :model="addBlogForm">
        <a-form-item
          field="title"
          label="标题"
          :rules="[
            { required: true, message: 'title is required' },
            { minLength: 5, message: 'must be greater than 5 characters' },
          ]"
          :validate-trigger="['change', 'input']"
        >
          <a-input v-model="addBlogForm.title" />
        </a-form-item>
        <a-form-item field="content" label="文章内容">
          <a-input v-model="addBlogForm.content" />
        </a-form-item>
        <a-form-item field="tags" label="tags">
          <a-space direction="vertical" size="large">
            <a-radio-group v-model="addBlogForm.tags.type">
              <a-radio value="娱乐">娱乐</a-radio>
              <a-radio value="编程">编程</a-radio>
              <a-radio value="周易">周易</a-radio>
              <a-radio value="八卦">八卦</a-radio>
            </a-radio-group>
            <a-radio-group v-model="addBlogForm.tags.lang">
              <a-radio value="PHP">PHP</a-radio>
              <a-radio value="JS">JS</a-radio>
              <a-radio value="GOLANG">GOLANG</a-radio>
              <a-radio value="JAVA">JAVA</a-radio>
            </a-radio-group>
          </a-space>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import { computed, ref, reactive, watch, nextTick } from 'vue';
  import { useI18n } from 'vue-i18n';
  import useLoading from '@/hooks/loading';
  import {
    queryBlogList,
    Blog,
    BlogParams,
    addBlog,
    delBlog,
  } from '@/api/blog';
  import { NewPagination } from '@/types/global';
  import type { SelectOptionData } from '@arco-design/web-vue/es/select/interface';
  import type { TableColumnData } from '@arco-design/web-vue/es/table/interface';
  import cloneDeep from 'lodash/cloneDeep';
  import Sortable from 'sortablejs';
  import { Message } from '@arco-design/web-vue';
  import moment from 'moment';

  type SizeProps = 'mini' | 'small' | 'medium' | 'large';
  type Column = TableColumnData & { checked?: true };

  const generateFormModel = () => {
    return {
      title: '',
      publishedAtStart: '',
      publishedAtEnd: '',
      status: '',
    };
  };
  const { loading, setLoading } = useLoading(true);
  const { t } = useI18n();
  const renderData = ref<Blog[]>([]);
  const formModel = ref(generateFormModel());
  const cloneColumns = ref<Column[]>([]);
  const showColumns = ref<Column[]>([]);

  const size = ref<SizeProps>('medium');

  const basePagination: NewPagination = {
    page: 1,
    limit: 10,
  };
  const pagination = reactive({
    ...basePagination,
  });
  const densityList = computed(() => [
    {
      name: t('blogList.size.mini'),
      value: 'mini',
    },
    {
      name: t('blogList.size.small'),
      value: 'small',
    },
    {
      name: t('blogList.size.medium'),
      value: 'medium',
    },
    {
      name: t('blogList.size.large'),
      value: 'large',
    },
  ]);
  const columns = computed<TableColumnData[]>(() => [
    {
      title: t('blogList.columns.id'),
      dataIndex: 'id',
    },
    {
      title: t('blogList.columns.title'),
      dataIndex: 'title',
    },
    {
      title: t('blogList.columns.author'),
      dataIndex: 'author',
    },
    {
      title: t('blogList.columns.content'),
      dataIndex: 'content',
    },
    {
      title: t('blogList.columns.status'),
      dataIndex: 'status',
      slotName: 'status',
    },
    {
      title: t('blogList.columns.createdAt'),
      dataIndex: 'createdAt',
      slotName: 'createdAt',
    },
    {
      title: t('blogList.columns.updatedAt'),
      dataIndex: 'updatedAt',
      slotName: 'updateAt',
    },
    {
      title: t('blogList.columns.operations'),
      dataIndex: 'operations',
      slotName: 'operations',
    },
  ]);

  const statusOptions = computed<SelectOptionData[]>(() => [
    {
      label: t('blogList.form.status.1'),
      value: 1,
    },
    {
      label: t('blogList.form.status.2'),
      value: 2,
    },
  ]);
  const fetchData = async (params: BlogParams = { page: 1, limit: 10 }) => {
    setLoading(true);
    try {
      const { data } = await queryBlogList(params);
      renderData.value = data.items;
      pagination.page = params.page;
      pagination.total = data.total;
    } catch (err) {
      // you can report use errorHandler or other
    } finally {
      setLoading(false);
    }
  };

  const search = () => {
    fetchData({
      ...basePagination,
      ...formModel.value,
    } as unknown as BlogParams);
  };
  const onPageChange = (page: number) => {
    fetchData({ ...basePagination, page });
  };

  fetchData();
  const reset = () => {
    formModel.value = generateFormModel();
  };

  const handleSelectDensity = (
    val: string | number | Record<string, any> | undefined,
    e: Event
  ) => {
    size.value = val as SizeProps;
  };

  const handleChange = (
    checked: boolean | (string | boolean | number)[],
    column: Column,
    index: number
  ) => {
    if (!checked) {
      cloneColumns.value = showColumns.value.filter(
        (item) => item.dataIndex !== column.dataIndex
      );
    } else {
      cloneColumns.value.splice(index, 0, column);
    }
  };

  const exchangeArray = <T extends Array<any>>(
    array: T,
    beforeIdx: number,
    newIdx: number,
    isDeep = false
  ): T => {
    const newArray = isDeep ? cloneDeep(array) : array;
    if (beforeIdx > -1 && newIdx > -1) {
      // 先替换后面的，然后拿到替换的结果替换前面的
      newArray.splice(
        beforeIdx,
        1,
        newArray.splice(newIdx, 1, newArray[beforeIdx]).pop()
      );
    }
    return newArray;
  };

  const popupVisibleChange = (val: boolean) => {
    if (val) {
      nextTick(() => {
        const el = document.getElementById('tableSetting') as HTMLElement;
        const sortable = new Sortable(el, {
          onEnd(e: any) {
            const { oldIndex, newIndex } = e;
            exchangeArray(cloneColumns.value, oldIndex, newIndex);
            exchangeArray(showColumns.value, oldIndex, newIndex);
          },
        });
      });
    }
  };

  watch(
    () => columns.value,
    (val) => {
      cloneColumns.value = cloneDeep(val);
      cloneColumns.value.forEach((item, index) => {
        item.checked = true;
      });
      showColumns.value = cloneDeep(cloneColumns.value);
    },
    { deep: true, immediate: true }
  );

  const addVisible = ref(false);
  const addCancel = () => {
    addVisible.value = false;
  };

  const handleClick = () => {
    addVisible.value = true;
  };

  const handleBeforeOk = async () => {
    await addBlog(addBlogForm);
    Message.success('新增成功');
    return true;
  };
  const addBlogForm = reactive({
    title: '',
    content: '',
    status: '1',
    tags: {
      lang: '',
      type: '',
    },
  });
  const optDelBlog = async (id: number) => {
    await delBlog(id);
    Message.success('删除成功');
    fetchData();
    return true;
  };
</script>

<script lang="ts">
  export default {
    name: 'BlogList',
  };
</script>

<style scoped lang="less">
  .container {
    padding: 0 20px 20px 20px;
  }
  :deep(.arco-table-th) {
    &:last-child {
      .arco-table-th-item-title {
        margin-left: 16px;
      }
    }
  }
  .action-icon {
    margin-left: 12px;
    cursor: pointer;
  }
  .active {
    color: #0960bd;
    background-color: #e3f4fc;
  }
  .setting {
    display: flex;
    align-items: center;
    width: 200px;
    .title {
      margin-left: 12px;
      cursor: pointer;
    }
  }
</style>
